package com.xncoding.tomcat.socket02;

import com.xncoding.tomcat.socket01.HttpProtocolUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response {

    /**
     * 响应信息
     */
    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    /**
     * 根据 url 拼接绝对路径，根据绝对路径再读取文件资源，再响应
     *
     * @param url 请求 url
     */
    public void outputHtml(String url) throws IOException {
        // 获取 url 资源的全路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(url);
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            // 输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }

}